package com.bonc.excel.entity;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author: wujing
 * @Date: 2024/9/6 15:14
 * @Description: TODO
 **/
@Getter
@Setter
@Accessors(chain = true)
@TableName("cate_cnf_col")
public class ColDto extends BaseEntity{


    @TableField("categroy_code")
    private String categroyCode;

    @TableField("col_name")
    private String colName;

    @TableField("col_level")
    private String colLevel;



    public static List<ColDto> setColData() {
        List<ColDto> objects = Lists.newArrayList();
        ColDto col1 = new ColDto();
        col1.setColName("模型（表）注册");
        col1.setColLevel("1");
        objects.add(col1);

        ColDto col2 = new ColDto();
        col2.setColName("本期新增/下线/累计数/注册率");
        col2.setColLevel("1_1");
        objects.add(col2);

        ColDto col3 = new ColDto();
        col3.setColName("模型（算法）注册 ");
        col3.setColLevel("2");
        objects.add(col3);

        ColDto col4 = new ColDto();
        col4.setColName("本期新增/下线/累计数/注册率");
        col4.setColLevel("2_1");
        objects.add(col4);



        ColDto col5 = new ColDto();
        col5.setColName("3");
        col5.setColLevel("3");
        objects.add(col5);

        ColDto col6 = new ColDto();
        col6.setColName("4");
        col6.setColLevel("4");
        objects.add(col6);

     /*   List<Col> objects = Lists.newArrayList();
        Col col1 = new Col();
        col1.setColName("【低效期】");
        col1.setColLevel("2_2_1");
        objects.add(col1);

        Col col2 = new Col();
        col2.setColName("衰退期/归档期/销毁期");
        col2.setColLevel("2_2");
        objects.add(col2);

        Col col3 = new Col();
        col3.setColName("【有效期】");
        col3.setColLevel("2_1_1");
        objects.add(col3);


        Col col4 = new Col();
        col4.setColName("生成期/活动期");
        col4.setColLevel("2_1");
        objects.add(col4);


        Col col5 = new Col();
        col5.setColName("数据全生命周期");
        col5.setColLevel("2");
        objects.add(col5);

        Col col6 = new Col();
        col6.setColName("表总数/其中有效期占比");
        col6.setColLevel("1");
        objects.add(col6);*/

      /*  Col col7 = new Col();
        col7.setColName("2_1_1");
        col7.setColLevel("2_1_1");
        objects.add(col7);


        Col col9 = new Col();
        col9.setColName("2_2_2");
        col9.setColLevel("2_2_2");
        objects.add(col9);

        Col col11 = new Col();
        col11.setColName("2_1_3");
        col11.setColLevel("2_1_3");
        objects.add(col11);

        Col col8 = new Col();
        col8.setColName("2_1_2");
        col8.setColLevel("2_1_2");
        objects.add(col8);
*/


        return objects;
    }

    /**
     *
     * @param param
     * @return
     *  //  1_1_1  构建为 1   1_1   1_1_1
     */
    public static Set<String> genCol(String param) {
        Set<String> cols = Sets.newHashSet();
        for (int i = 1; i <= param.length(); i++) {
            if(i%2 ==0){
                continue;
            }
            cols.add(param.substring(0, i));
        }
        return cols;
    }


    /**
     * 构建表头处理单元格是否合并
     * @param params 列表头数据以及格式
     * @return
     */
    public static LinkedHashMap<String, List<String>> getColTitle(List<ColDto> params) {
        if(CollectionUtil.isEmpty(params)){
            return null;
        }

        //col全量数据
        Map<String, String> colMap = params.stream()
                .collect(Collectors.toMap(ColDto::getColLevel, ColDto::getColName,(k1, k2) -> k1));

        //拿到 1  2  3  4...对应得数据 获取需要单元格合并得数据
        Map<String, List<ColDto>> sortedMap = params.stream().collect(Collectors.groupingBy(v -> v.getColLevel().split("_")[0]));
        // long count = params.stream().map(p -> p.getColLevel().split("_")[0]).count();
        // key升序排序
         sortedMap = sortedMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        // 解决可能存在的键冲突问题，默认保留第一个值
                        (oldValue, newValue) -> oldValue,
                        // 提供一个新的TreeMap实例作为收集器，用于保持排序
                        () -> new TreeMap<>()
                ));
        LinkedHashMap<String, List<String>> linkedHashMap = Maps.newLinkedHashMap();
        //列数控制
        AtomicInteger colCount = new AtomicInteger(1);
        //遍历第一列 第二列 ....  key为从1开始得整数
        sortedMap.forEach((key,value)->{
            //处理第key列单元格(单元格合并问题)

            //只有一列 不用考虑合并
            if(value.size() == 1){
                List<String> tempList = Lists.newArrayList();
                tempList.add(value.get(0).getColName());
                linkedHashMap.put(String.valueOf(colCount.get()),tempList);
                colCount.getAndIncrement();
                return;
            }
           /* if(value.size() == 2){
                // 1  1_1  直接拿到1_1
                Col col = value.stream().filter(v -> v.getColLevel().startsWith(key + "_")).findFirst().get();
                tempList.add(colMap.get(key));
                tempList.add(col.getColName());
               // linkedHashMap.put(key,tempList);
                linkedHashMap.put(String.valueOf(colCount.get()),tempList);
                colCount.getAndIncrement();
                return;
            }*/

            //以下考虑单元格合并问题  比如存在格式  1_1_1  1_1_2

            //level降序
            Collections.sort(value, (a, b) -> b.getColLevel().compareTo(a.getColLevel()));
            ColDto col = value.get(0);
            //获取_出现最长次数
            long longestCount = col.getColLevel().chars().filter(ch -> ch == '_').count();
            List<ColDto> longestList = value.stream().filter(cols -> cols.getColLevel().chars()
                    .filter(ch -> ch == '_').count() == longestCount).collect(Collectors.toList());
            //level升序
            Collections.sort(longestList, (a, b) -> a.getColLevel().compareTo(b.getColLevel()));
            // longestList有几个就有几个单元格需要合并
            longestList.forEach(tempCol -> {
                List<String> tempList = Lists.newArrayList();
                //  1_1_1  构建为 1   1_1   1_1_1
                Set<String> cols = genCol(tempCol.getColLevel());
                cols.forEach(s -> { tempList.add(colMap.get(s));});
                linkedHashMap.put(String.valueOf(colCount.get()),tempList);
                colCount.getAndIncrement();
            });
        });
        return linkedHashMap;
    }



}
